package com.star.mall.persistence.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.star.mall.base.exception.BusinessException;
import com.star.mall.base.query.Query;
import com.star.mall.base.response.BaseResponse;
import com.star.mall.constants.KeyConstant;
import com.star.mall.model.PasswordParam;
import com.star.mall.persistence.entity.Role;
import com.star.mall.persistence.entity.User;
import com.star.mall.persistence.mapper.UserMapper;
import com.star.mall.persistence.service.IRoleService;
import com.star.mall.persistence.service.IUserScoreService;
import com.star.mall.persistence.service.IUserService;
import com.star.mall.utils.ContextUtil;
import com.star.mall.utils.UniqueIdUtil;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author StarQ
 * @since 2020-12-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    IRoleService roleService;
    @Resource
    IUserScoreService userScoreService;

    @Override
    public Page<User> queryRoleUsers(Query<User> query) {
        return baseMapper.queryRoleUsers(query.getPage(), query.toWrapper(currentModelClass()));
    }

    @Override
    public IPage<User> queryOrgUsers(Query<User> query) {
        return baseMapper.queryOrgUsers(query.getPage(), query.toWrapper(currentModelClass()));
    }

    @Override
    @Cacheable(value = KeyConstant.USER_CACHE_NAME, key = "#username")
    public User getByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account_", username);
        User user = baseMapper.selectOne(wrapper);
        List<Role> roles = roleService.getRolesByUserId(user.getId());
        user.setRoles(roles);
        return user;
    }

    @Override
    public BaseResponse<String> modifyPassword(PasswordParam passwordParam) {

        if (!passwordParam.getNewPassword().equals(passwordParam.getRepeatPassword())) {
            throw new BusinessException("新密码与重复密码不一致");
        }
        String userId = ContextUtil.getCurrentUserId();
        User user = getById(userId);
        if (!passwordEncoder.matches(passwordParam.getOldPassword(), user.getPassword())) {
            throw new BusinessException("旧密码错误");
        }
        user.setPassword(passwordEncoder.encode(passwordParam.getNewPassword()));
        baseMapper.updateById(user);
        return BaseResponse.success("修改成功");
    }

    @Override
    public boolean save(@Validated User user) {
        user.setId(UniqueIdUtil.getSid());
        userScoreService.initScore(Optional.ofNullable(user.getScore()).orElse(0), user.getId());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return baseMapper.insert(user) >= 1;
    }

    @Override
    @CacheEvict(value = KeyConstant.USER_CACHE_NAME, key = "#user.account")
    public boolean updateById(User user) {
        return super.updateById(user);
    }

}
